<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-12-10
 * Time: 14:16
 */
namespace app\api\controller\v1;
use app\api\controller\BaseController;
use app\api\model\Currency;
use app\api\model\GfActivityOrder;
use app\api\model\GrActivityOrder;
use app\api\model\SjActivityOrder;
use app\api\model\UserAssetsAuth;
use app\api\model\UserAuth;
use app\api\model\UserAuthLike;
use app\api\model\UserAuthShare;
use app\api\model\UserAuthZan;
use app\api\model\UserEducationAuth;
use app\api\model\UserIncomeAuth;
use app\api\model\UserInvitation;
use app\api\model\UserJobAuth;
use app\api\model\UserMoney;
use app\api\model\UserPrivacy;
use app\api\model\UserPrivacyList;
use app\api\model\UserRealAuth;
use app\api\service\CreateUserAuth;
use app\api\service\UserPhone;
use app\api\service\UserToken;
use app\api\validate\CheckUserAuth;
use app\api\validate\PhoneGet;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\facade\Log;
use think\facade\Request;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;

class User extends BaseController
{
    /**
     * 更新用户信息并返回用户最新信息
     * @http put
     * @url user
     */
    public function updateUser()
    {
        Log::init([
            'type' => 'File'
        ]);
        $uid = TokenService::getCurrentUid();
        $put = Request::put();
        $user = new UserModel();
        $userInfo = UserModel::get($uid);
        if($userInfo['status'] == 1){
            $user_no = date('Ym');
            $user_num = UserModel::where('user_no',$user_no)->count();
            $user_num = $user_num + 1;
            $user_num = getStringLen($user_num);
            Db::startTrans();
            try {
                $user->allowField(true)->save([
                    'nickname' => $put['nickname'],
                    'head_img' => $put['head_img'],
                    'province' => $put['province'],
                    'status' => 2,
                    'city' => $put['city'],
                    'gender' => $put['gender'],
                    'user_no' => $user_no,
                    'user_num' => $user_num,
                ],['id' => $uid]);
                $this->createUserPrivacy();
                $this->createCurrency();
                Db::commit();
                return json([],202);
            }
            catch (Exception $e){
                Db::rollback();
                Log::write('更新用户信息:'.$e,'error');
                return false;
            }
        } else {
            $user->allowField(true)->save([
                'nickname' => $put['nickname'],
                'head_img' => $put['head_img'],
                'province' => $put['province'],
                'city' => $put['city'],
                'gender' => $put['gender']
            ],['id' => $uid]);
            return json([],202);
        }
    }

    /**
     * 添加用户隐私表
     */
    protected function createUserPrivacy()
    {
        $openId = TokenService::getCurrentTokenVar("openid");
        UserPrivacy::create([
            'openid' => $openId,
            'real_auth_type' => 1,
            'education_auth_type' => 1,
            'phone_type' => 1,
            'name_type' => 1,
            'occupation_type' => 1,
        ]);
    }

    /**
     * 登录添加甜茶币
     */
    protected function createCurrency()
    {
        $user = TokenService::getUserInfo();
        $date = date('Y-m-d');
        $info = Currency::where('day_date',$date)
            ->where('status',1)
            ->where('openid',$user['openid'])
            ->find();
        if(!$info) {
            $end_time = time() + 604800;
            Currency::create([
                'openid' => $user['openid'],
                'number' => 25,
                'type' => 1,
                'status' => 1,
                'end_time' => $end_time,
                'day_date' => $date,
                'min_number' => 25,
                'msg_json' => json_encode($user)
            ]);
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $this->createCurrency();
        $info = TokenService::getUserInfo();
        $info['auth_count'] = 0;
        // 实名认证
        $info['auth_real'] = UserRealAuth::where('openid',$info['openid'])
            ->with('justImg,backImg')->find();
        if($info['auth_real']['status'] == 2) {
            $info['auth_count'] = $info['auth_count'] + 1;
        }
        // 手机认证
        $info['auth_phone'] = $info['phone'];
        if($info['auth_phone']) {
            $info['auth_count'] = $info['auth_count'] + 1;
        }
        // 学历认证
        $info['auth_education'] = UserEducationAuth::where('openid',$info['openid'])->find();
        if($info['auth_education']['status'] == 2) {
            $info['auth_count'] = $info['auth_count'] + 1;
        }
        // 工作证明
        $info['auth_job'] = UserJobAuth::where('openid',$info['openid'])
            ->with('jobImg')->find();
        if($info['auth_job']['status'] == 2) {
            $info['auth_count'] = $info['auth_count'] + 1;
        }
        // 收入证明
        $info['auth_income'] = UserIncomeAuth::where('openid',$info['openid'])
            ->with('incomeImg')->find();
        if($info['auth_income']['status'] == 2) {
            $info['auth_count'] = $info['auth_count'] + 1;
        }
        // 资产证明
        $info['auth_assets'] = UserAssetsAuth::where('openid',$info['openid'])
            ->with('assetsImg')->find();
        if($info['auth_assets']['status'] == 2) {
            $info['auth_count'] = $info['auth_count'] + 1;
        }
        $info['user_auth'] = UserAuth::where('openid',$info['openid'])->with('imgs.img')->find();
        $date = date('Y-m-d');
        $info['denglu'] = Currency::where('status',1)
            ->where('type',1)
            ->where('openid',$info['openid'])
            ->where('day_date',$date)
            ->find();
        $info['zan'] = Currency::where('status',5)
            ->where('type',1)
            ->where('openid',$info['openid'])
            ->where('day_date',$date)
            ->find();
        $info['share'] = Currency::where('status',6)
            ->where('type',1)
            ->where('openid',$info['openid'])
            ->where('day_date',$date)
            ->find();
        // 用户隐私设置信息
        $info['user_privacy'] = UserPrivacy::where('openid',$info['openid'])
            ->find();
        // 来往数量
        $one = UserPrivacyList::where('y_openid',$info['openid'])->count();
        $two = UserPrivacyList::where('b_openid',$info['openid'])->count();
        $info['user_privacy_count'] = $one + $two;
        // 喜欢数量
        $like_one = UserAuthLike::where('openid',$info['openid'])->count();
        $like_two = UserAuthLike::where('user_auth_openid',$info['openid'])->count();
        $info['like_num'] = $like_one + $like_two;
        // 甜茶币数量
        $term = Currency::where('end_time','eq',null)->sum('min_number');
        $no_term = Currency::where('end_time','gt',time())->sum('min_number');
        $info['currency_num'] = $term + $no_term;
        // 活动数量
        $gfActivityNum = GfActivityOrder::where('openid','eq',$info['openid'])
            ->where('status','gt',1)
            ->count();
        $grActivityNum = GrActivityOrder::where('openid','eq',$info['openid'])
            ->count();
        $sjActivityNum = SjActivityOrder::where('openid','eq',$info['openid'])
            ->where('status','gt',1)
            ->count();
        $info['activity_num'] = $gfActivityNum+$grActivityNum+$sjActivityNum;
        return $info;
    }

    /**
     * 甜茶币过期减去过期甜茶币
     * 1. 获取可用甜茶币
     * 2. 获取全部失去的
     * 4. 当前值 = 没有过期的 - 已经使用的
     */
    protected function minCurrency()
    {
        $time = time();
        $currency_one = Currency::where('type',1)->where('end_time','neq',null)->where('end_time','gt',$time)->sum('number');
    }

    /**
     * 更新用户二维码
     */
    public function setInviteImg()
    {
//        $uid = TokenService::getCurrentUid();
//        $userToken = new UserToken();
//        $userToken->setCode($uid,'user');
    }



    /**
     * 获取手机号
     */
    public function getPhone()
    {
        $uid = TokenService::getCurrentUid();
        (new PhoneGet())->goCheck();
        $up = new UserPhone();
        $post = Request::post();
        $up->get($post);
        $userInfo = UserModel::where('id',$uid)->find();
        $userInfo['all_money'] = UserMoney::where('user_id',$uid)->where('type',1)->sum('money');
        $userInfo['ti_money'] = UserMoney::where('user_id',$uid)->where('type',2)->sum('money');
        return UserModel::get($uid);
    }

    /**
     * 绑定上下级
     *  下级没有下单重新绑定
     */
    public function createInvite($openid)
    {
        $openidSelf = TokenService::getCurrentTokenVar('openid');
        $user = UserModel::where('openid',$openid)->find();
        if($user) {
            if ($openid != $openidSelf) {
                $invite = UserInvitation::where('invitee', 'eq', $openidSelf)
                    ->find();
                if (!$invite) {
                    UserInvitation::create([
                        'inviter' => $openid,
                        'invitee' => $openidSelf,
                    ]);
                }
            }
        }
    }

    // 获取一级下级信息
    public function getInviteList()
    {
        $uid = TokenService::getCurrentUid();
        $list = UserInvitation::hasWhere('user',['status'=>1])
            ->where('user_invitation.inviter_id',$uid)
            ->with('user')
            ->order('user_invitation.id desc')->select()->toArray();
        if(count($list) > 0) {
            $user = [];
            foreach ($list as $k=>$v){
                $user[$k] = $v['user'];
            }
            return $user;
        }else {
            return [];
        }
    }

    /**
     * 上墙信息操作
     */
    public function updateUserAuth()
    {
        (new CheckUserAuth())->goCheck();
        $put = Request::put();
        $userAuth = new CreateUserAuth($put);
        return $userAuth->entrance();
    }

    /**
     * 更新用户上墙状态
     */
    public function updateUserAuthState()
    {
        $userAuth = UserAuth::where('openid',TokenService::getCurrentTokenVar("openid"))->find();
        if($userAuth) {
            $userAuth->state = 1;
            $userAuth->save();
            return writeJson(201, [], '已取消上墙');
        }
    }
}